package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.utils.StreamUtils;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.domain.dto.SysCustomDto;
import com.sale.system.domain.FieldsJson;
import com.sale.system.domain.PullDown;
import com.sale.system.domain.SysFields;
import com.sale.system.domain.SysTable;
import com.sale.system.mapper.SysFieldsMapper;
import com.sale.system.mapper.SysTableMapper;
import com.sale.system.service.ISysFieldsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 获取表字段
 * @Date 23-06-13
 * @Author hl
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class SysFieldsServiceImpl implements ISysFieldsService {

    private final SysFieldsMapper sysFieldsMapper;

    private final SysTableMapper sysTableMapper;


    /**
     * 查询字段信息
     *
     * @param path 表名
     * @return list
     */
    @Override
    public List<PullDown> selectSysFields(String path) {
        path = path.substring(1);
        //需要先根据地址查询表名
        String table = sysFieldsMapper.selectTableMenu(path);
        //redisService.deleteObject(table);
        //先查询缓存里是否存在这个key值
        boolean flag = RedisUtils.isExistsObject(table);
        List<PullDown> list = null;
        if (flag) {
            return RedisUtils.getCacheList(table);
        } else {
            list = sysFieldsMapper.selectSysFieldsPull(table);
            if (list.size() > 0) {
                //缓存
                RedisUtils.setCacheList(table, list);
            }
        }
        return list;
    }

    @Override
    public String insertFieldsJson(FieldsJson fieldsJson) {
        return null;
    }

    /**
     * 根据条件分页查询自定义表头
     *
     * @param sysFields 自定义表头信息
     * @return 用户信息集合信息
     */
    @Override
    public TableDataInfo<SysFields> selectSysColumn(SysFields sysFields, PageQuery pageQuery) {
        Page<SysFields> page = sysFieldsMapper.selectPageFieldsList(pageQuery.build(), this.buildQueryWrapper(sysFields));
        return TableDataInfo.build(page);
    }

    /**
     * 新增自定义表头
     *
     * @param fields 自定义表头信息
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFields(SysFields fields) {
        //新增自定义表头
        int rows = sysFieldsMapper.insert(fields);
        //往对应表增加表字段
        sysTableMapper.insertTable(sealTable(fields));
        //缓存自定义表头
        commonCache();
        return rows;
    }

    //缓存自定义表头
    private void commonCache() {
        String userIdStr = LoginHelper.getUserIdStr();
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        List<SysCustomDto> listCustom = sysFieldsMapper.selectCustom();
        Map<String, List<SysCustomDto>> customMap = StreamUtils.groupByKey(listCustom, SysCustomDto::getTableName);
        String ginseng2 = CacheNames.SYS_CUSTOM + "_" + tenantId;
        customMap.forEach((k, v) -> {
            CacheUtils.put(ginseng2, k, v);
        });
    }

    /**
     * 修改自定义表头
     *
     * @param fields 自定义表头信息
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateFields(SysFields fields) {
        //修改表头
        int rows = sysFieldsMapper.updateById(fields);
        //往对应表修改表字段
        sysTableMapper.updateTable(sealTable(fields));
        //缓存自定义表头
        commonCache();
        return rows;
    }

    /**
     * 删除自定义表头
     *
     * @param fieldsId 自定义表头信息
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFieldsByIds(long fieldsId) {
        SysFields sysFields = sysFieldsMapper.selectFieldsById(fieldsId);
        int rows = sysFieldsMapper.deleteById(fieldsId);
        sysTableMapper.deleteTableById(sealTable(sysFields));
        //缓存自定义表头
        commonCache();
        return rows;
    }


    /**
     * 自定义表头封装返回
     *
     * @param fields 自定义表头信息
     * @return SysTable
     */
    private SysTable sealTable(SysFields fields) {
        String tableName = sysFieldsMapper.selectTableName(fields.getMenuId());
        SysTable sysTable = new SysTable();
        sysTable.setTableName(tableName);
        sysTable.setTableHead(fields.getFieldsModel());
        sysTable.setTableComment(fields.getFieldsTag());
        int type = fields.getFieldsType();
        if (type == 1) {
            //文本
            sysTable.setTableType("varchar(255)");
        } else {
            //日期格式
            sysTable.setTableType("datetime");
        }
        return sysTable;
    }

    private Wrapper<SysFields> buildQueryWrapper(SysFields fields) {
        Map<String, Object> params = fields.getParams();
        QueryWrapper<SysFields> wrapper = Wrappers.query();
        wrapper
            .eq(ObjectUtil.isNotNull(fields.getFieldsTag()), "t1.fields_tag", fields.getFieldsTag())
            .eq(StringUtils.isNotBlank(fields.getFieldsModel()), "t1.fields_model", fields.getFieldsModel())
            .eq(StringUtils.isNotBlank(fields.getMenuName()), "t2.menu_name", fields.getMenuName()).between(params.get("beginTime") != null && params.get("endTime") != null,
                "t1.create_time", params.get("beginTime"), params.get("endTime"));
        return wrapper;
    }

    /**
     * 根据菜单路由查询动态表头集合转驼峰
     */
    @Override
    public Map<String, String> getCaseList(String path) {
        List<SysFields> list = sysFieldsMapper.selectCaseList(path);
        Map<String, String> map = new HashMap<>();
        for (SysFields entity : list) {
            map.put(entity.getFieldsModel(), "");
            map.put("fieldsTag", entity.getFieldsTag());
            map.put("fieldsModel", entity.getFieldsModel());
            map.put("menuId", String.valueOf(entity.getMenuId()));
            map.put("fieldsType", String.valueOf(entity.getFieldsType()));
        }
        return map;
    }
}
